package com.kaixinff.kaixin001.servlet;

import java.io.IOException;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.json.JSONObject;

import com.kaixinff.kaixin001.util.Filter;
import com.kaixinff.kaixin001.util.KXClient;
import com.kaixinff.kaixin001.util.KXUtil;
import com.kaixinff.kaixin001.util.RegStep;
import com.kaixinff.name.User;

@SuppressWarnings("serial")
public class MarketServlet extends HttpServlet {

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/html; charset=" + KXUtil.CHARSET);
		List<User> users = KXUtil.getUsers(new Filter(){
			@Override
			public boolean access(User user) {
				return user.hasStep(RegStep.ADD_XW);
			}}, resp);
		if (users == null) {
			return;
		}
		
		for (User user: users) {
			KXClient client = KXClient.getInstance(user.getId());
			String url = KXUtil.HOST_URL + "/!spiderman/market.php";
			String html = client.doGet(url, null).getContent();
			Pattern p = Pattern.compile("\"suncoin\":\"(\\d+?)\"");
			Matcher m = p.matcher(html);
			if (m.find()) {
				int suncoin = Integer.parseInt(m.group(1));
				if (suncoin >= 100 && suncoin < 150) {
					String iid = "612";
					p = Pattern.compile("javascript\\:buyMarketInv\\('timeInv','" + iid + "',\\$j\\('#limitinv_offprice_" + iid + "'\\).val\\(\\),0,'(.+?)'\\);");
					m = p.matcher(html);
					if (m.find()) {
						String buyurl = KXUtil.HOST_URL + "/!spiderman/!ajax_market_buy.php?buyType=timeInv&buyCount=1&iid=" + iid + "&rt=json&cid=" + getCid(html) + "&tmp=" + Math.random();
						html = client.doGet(buyurl, url).getContent();
						try {
							JSONObject jobj = new JSONObject(html);
							if (jobj.getString("flag").equals("suc")) {
								System.out.println(user.getId() + ": " + KXUtil.findMessage(jobj.getString("html")));
							} else {
								System.err.println(html);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}
				}
			}
		}
	}
	
	private String getCid(String html) {
		Pattern p = Pattern.compile("\"cid\"[:]\"(\\d+?)\"");
		Matcher m = p.matcher(html);
		if (m.find()) {
			return m.group(1);
		}
		return "2";		
	}
}
